package plugins

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

const (
	OriginField      = "Origin"
	AllowOrigin      = "Access-Control-Allow-Origin"
	AllowMethods     = "Access-Control-Allow-Methods"
	AllowHeaders     = "Access-Control-Allow-Headers"
	AllowCredentials = "Access-Control-Allow-Credentials"
	ExposeHeaders    = "Access-Control-Expose-Headers"
)

// Cors 跨域处理中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.GetHeader(OriginField) //请求头部
		if origin != "" {
			// 可将 * 替换为指定的域名
			c.Header(AllowOrigin, origin)
			c.Header(AllowMethods, "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header(AllowHeaders, "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header(ExposeHeaders,
				"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header(AllowCredentials, "true")
		}

		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
